package com.example.hfweather.ui.video

import android.os.Bundle
import android.view.LayoutInflater
import androidx.core.net.toUri
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import com.example.hfweather.base.BaseBindingActivity
import com.example.hfweather.databinding.AcMedia3PlayerBinding

class Media3PlayerActivity : BaseBindingActivity<AcMedia3PlayerBinding>() {

    private var player: ExoPlayer? = null
    private var playWhenReady = true
    private var currentWindow = 0
    private var playbackPosition = 0L
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun initBinding(layoutInflater: LayoutInflater): AcMedia3PlayerBinding {
        return AcMedia3PlayerBinding.inflate(layoutInflater)
    }

    /**
     * activity 开始时初始化播放器
     */
    override fun onStart() {
        super.onStart()
        initPlayer()
    }
    /**
     * activity 停止时销毁播放器
     */
    override fun onStop() {
        super.onStop()
        releasePlayer()
    }

    /**
     * 初始化播放器
     *
     * 该函数负责创建和配置ExoPlayer实例，设置播放器视图，并准备播放本地视频资源。
     * 播放器会从指定的原始资源文件中加载视频内容，并根据保存的状态设置初始播放位置。
     */
    private fun initPlayer() {
        player = ExoPlayer.Builder(this).build().also { exoPlayer ->
            binding.playerView.player = exoPlayer
            //从本地读取视频文件播放
            val rawUri= "android.resource://${packageName}/raw/aaa".toUri()
            val mediaItem = MediaItem.fromUri(rawUri)
            exoPlayer.setMediaItem(mediaItem)
            exoPlayer.playWhenReady = playWhenReady//保存的播放状态
            exoPlayer.seekTo(currentWindow, playbackPosition)//保存的播放位置
            exoPlayer.prepare()
        }

    }

    /**
     * 销毁播放器
     */
    private fun releasePlayer() {
        player?.let { exoPlayer ->
            playbackPosition = exoPlayer.currentPosition
            currentWindow = exoPlayer.currentMediaItemIndex
            playWhenReady = exoPlayer.playWhenReady
            exoPlayer.release()
        }
        player = null
    }
}